package com.xiaoai.io.bio6_chat_demo;

import java.io.*;
import java.net.Socket;

/**
 * @Author
 * @Date 2021-09-06 22:34
 */
public class ServerReaderThread extends Thread{

    private Socket socket;
    public ServerReaderThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {

        try {
            // 得到数据输入流读取客户端发送的数据
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            while ((msg = br.readLine()) != null){
                System.out.println("服务器收到["+socket.toString()+"]msg："+msg);
                sendMsgToAllClient(msg);
            }

        } catch (IOException e) {
            System.out.println(String.format("当前有人下线：[%s]",
                    socket.toString()));
            Server.allSocketOnLine.remove(socket);
        }
    }

    private void sendMsgToAllClient(String msg) throws IOException {
        for (Socket sk : Server.allSocketOnLine) {
            PrintStream ps = new PrintStream(sk.getOutputStream());
            ps.println(socket.toString() + ":" + msg);
            ps.flush();
        }
    }
}
